<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"
      xmlns="http://www.w3.org/1999/xhtml">
<head lang="en">
    <meta charset="UTF-8">
    <title>组织机构管理</title>
    <link rel="stylesheet" href="../../../assert/css/font.css" th:href="@{/assert/css/font.css}"/>
    <link rel="stylesheet" href="../../../assert/css/bootstrap.min.css" th:href="@{/assert/css/bootstrap.min.css}"/>
    <link rel="stylesheet" href="../../../assert/css/bootstrap-table.css" th:href="@{/assert/css/bootstrap-table.css}"/>
    <link rel="stylesheet" href="../../../assert/css/bootstrap-select.min.css"
          th:href="@{/assert/css/bootstrap-select.min.css}"/>
    <link rel="stylesheet" href="../../../assert/css/bootstrapValidator.css"
          th:href="@{/assert/css/bootstrapValidator.css}"/>
    <link rel="stylesheet" href="../../../assert/css/toastr.min.css" th:href="@{/assert/css/toastr.min.css}"/>
    <link href="../../../assert/js/lib/jqwidgets-ver4.0.0/jqwidgets/styles/jqx.base.css" rel="stylesheet"
          th:href="@{/assert/js/lib/jqwidgets-ver4.0.0/jqwidgets/styles/jqx.base.css}"/>
    <link rel="stylesheet" href="../../../assert/css/style.css" th:href="@{/assert/css/style.css}"/>
    <link rel="stylesheet" href="../../../assert/css/index.css"
          th:href="@{/assert/css/index.css(v_=${@commonController.getSysConfigByPK('CACHE_CODE')})}"/>
    <link rel="stylesheet" href="../../../assert/css/common.css" th:href="@{/assert/css/common.css}"/>
    <link href="../../../assert/css/plugin/jsTree/themes/default/style.css" rel="stylesheet"
          th:href="@{/assert/css/plugin/jsTree/themes/default/style.css}">
    <link rel="stylesheet" href="../../../assert/js/bootstrap-fileinput/css/fileinput.min.css"
          th:href="@{/assert/js/bootstrap-fileinput/css/fileinput.min.css}"/>
    <style>
        .importTips {
            margin-top: 20px;
        }

        .importTips li {
            line-height: 26px;
        }

        .importTips li span {
            padding-right: 5px;
        }
    </style>
</head>
<body class="laydate_body">
<div class="wrapper wrapper-content">
    <div class="ibox">
        <!--<div class="con-title">-->
        <!--<h4>组织机构</h4>-->
        <!--<div th:if="${area != null}" style="display: none">-->
        <!--<input type="hidden" th:value="${area.id}" id="areaIdHelp"/>-->
        <!--</div>-->
        <!--</div>-->
        <div class="resourceCon  organizCon clearfix">
            <div class="organizationTree">
                <div id="organizTree" class="scrollbar">
                </div>
            </div>
            <div class="resourceRight">
                <div class="con-operation clearfix">
                    <div class="cquery  clearfix">
                        <div class="search_group">
                            <label class="control-label">名称：</label>
                            <div class="control-inline">
                                <input type="text" class="form-control" id="nameSearch" placeholder="请输入名称">
                            </div>
                        </div>
                        <div class="search_group">
                            <label class="control-label">机构类型:</label>
                            <div class="control-inline">
                                <select id="mechanismType" class="selectpicker" data-live-search="true"
                                        data-live-search-style="begins" title="请选择状态" multiple>

                                </select>
                            </div>
                        </div>
                        <div class="search_group">
                            <label class="control-label">状态:</label>
                            <div class="control-inline">
                                <select id="statusSearch" class="selectpicker" data-live-search="true"
                                        data-live-search-style="begins" title="请选择状态" multiple>
                                    <option value="1">启用</option>
                                    <option value="0">停用</option>
                                </select>
                            </div>
                        </div>

                        <div class="search_group">
                            <button id="searchBtn" type="button" class=" querybtn btn btn-danger">查询</button>
                            <button id="reset" type="reset" class="btn  btn-default">重置</button>
                        </div>
                    </div>
                    <div class="obtns clearfix">
                        <button class="btn btn-default" type="button" data-toggle="modal" data-target="#groupModal">
                            <i class="fa fa-plus"></i>添加组织机构
                        </button>
                        <button id="editBtn" class="btn btn-default" type="button">
                            <i class="fa fa-pencil"></i>修改
                        </button>
                        <button id="batchDeleteBtn" class="btn btn-default" type="button" data-toggle="modal"><i
                                class="fa fa-trash"></i>删除
                        </button>
                        <button id="batchOnBtn" class="btn btn-default" type="button"><i
                                class="fa fa-power-off"></i>启用
                        </button>
                        <!--<button id="batchOffBtn" class="btn btn-default" type="button"><i-->
                        <!--class="fa fa-stop"></i>停用-->
                        <!--</button>-->
                        <button id="importBtn" class="btn btn-default" type="button" data-toggle="modal"
                                data-target="#importModal"><i
                                class="fa fa-upload"></i>导入
                        </button>
                        <button id="powerBtn" class="btn btn-default" type="button"><i
                                class="fa fa-get-pocket"></i>授权
                        </button>
                    </div>
                </div>
                <table id="groupTable"></table>
            </div>

            <!-- 组织机构管理Modal -->
            <div class="modal fade" id="groupModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
                 data-backdrop=false>
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                    aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title">添加组织机构</h4>
                        </div>
                        <div class="modal-body">
                            <form class="form-horizontal" role="form" id="groupForm">
                                <div class="form-group">
                                    <label class="col-sm-3 control-label">省份:</label>
                                    <div class="col-sm-9">
                                        <select class="mechanTypepicker selectpicker" name="areaid">
                                        </select>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="col-sm-3 control-label">所属组织机构:</label>
                                    <div class="col-sm-9">
                                        <input type="hidden" class="form-control" name="parentid"/>
                                        <input type="text" class="form-control" name="parentname" readonly
                                               placeholder="请选择所属组织机构" style="background: #fff">
                                        <div id="addTree" class="otree"></div>
                                    </div>
                                </div>

                                <div style="width:100%" class="clearfix">
                                    <div class="form-group formcom" style="width:58%;">
                                        <label class="col-sm-5 control-label" style="margin-left:-5px;"><span
                                                class="respan">*</span>名称:</label>
                                        <div class="col-sm-7">
                                            <input type="text" class="form-control" name="name" placeholder="请输入机构名称">
                                        </div>
                                    </div>
                                    <div class="form-group   formcom" style="width:42%;">
                                        <label class="col-sm-5 control-label"><span class="respan">*</span>类型:</label>
                                        <div class="col-sm-7">
                                            <select class="mechanTypepicker selectpicker" name="type" id="addType">
                                                <!--<option value="2" selected>部门</option>
                                                <option value="1">质检组</option>
                                                <option value="0">坐席组</option>-->
                                            </select>
                                        </div>
                                    </div>
                                </div>

                                <div style="width:100%" class="clearfix">
                                    <div class="form-group formcom" style="width:58%;">
                                        <label class="col-sm-5 control-label" style="margin-left:-5px;">排序:</label>
                                        <div class="col-sm-7">
                                            <input type="text" class="form-control" name="orderno" placeholder="请输入排序">
                                        </div>

                                    </div>
                                    <div class="form-group formcom" style="width:42%;">
                                        <label class="col-sm-5 control-label">启用否:</label>
                                        <div class="col-sm-7">
                                            <select class="enabledPicker selectpicker" name="status">
                                                <option value="1" selected>启用</option>
                                                <option value="0">停用</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-sm-3 control-label">备注:</label>
                                    <div class="col-sm-9">
                                        <textarea class="form-control" name="description"
                                                  placeholder="请输入内容"></textarea>
                                    </div>
                                </div>
                                <!--分配坐席组功能由授权来替换-->
                                <!--<div class="form-group" id="addRelationDiv">
                                    <label class="col-sm-3 control-label">分配坐席组：</label>
                                    <div class="col-sm-9">
                                        <div class="rrow clearfix" id="addRelationListDiv">
                                            &lt;!&ndash;"<div class='ritem'><input type='checkbox' name='seatGroupList' value='" + seat.id + "'/><span>" + seat.name + "</span></div>"&ndash;&gt;
                                        </div>
                                    </div>
                                </div>-->
                                <button type="reset" id="addResetBtn" hidden>重置</button>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="savebtn btn btn-primary" id="addSaveBtn">保存</button>
                            <button type="button" class="cancelbtn btn btn-default" data-dismiss="modal">取消</button>
                        </div>
                    </div>
                </div>
            </div>
            <!--组织机构修改modal -->
            <div class="modal fade" id="editGroupModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
                 data-backdrop=false>
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                    aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title">修改组织机构</h4>
                        </div>
                        <div class="modal-body">
                            <form class="form-horizontal" role="form" id="editGroupForm">
                                <input type="hidden" id="groupId" name="id" value=""/>
                                <div class="form-group">
                                    <label class="col-sm-3 control-label">省份：</label>
                                    <div class="col-sm-9">
                                        <select class="mechanTypepicker selectpicker" name="areaid">
                                        </select>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="col-sm-3 control-label">所属组织机构：</label>
                                    <div class="col-sm-9">
                                        <input type="hidden" class="form-control" name="parentid"/>
                                        <input type="text" class="form-control" name="parentname" readonly
                                               placeholder="请选择所属组织机构" style="background: #fff">
                                        <div id="editTree" class="otree"></div>
                                    </div>
                                </div>

                                <div style="width:100%" class="clearfix">
                                    <div class="form-group formcom" style="width:58%;">
                                        <label class="col-sm-5 control-label" style="margin-left:-5px;"><span
                                                class="respan">*</span>名称：</label>
                                        <div class="col-sm-7">
                                            <input type="text" class="form-control" name="name" placeholder="请输入机构名称">
                                        </div>
                                    </div>
                                    <div class="form-group   formcom" style="width:42%;">
                                        <label class="col-sm-5 control-label"><span class="respan">*</span>类型：</label>
                                        <div class="col-sm-7">
                                            <select class="mechanTypepicker selectpicker" name="type" id="editType">
                                                <!--<option value="2" selected>部门</option>
                                                <option value="1">质检组</option>
                                                <option value="0">坐席组</option>-->
                                            </select>
                                        </div>
                                    </div>
                                </div>

                                <div style="width:100%" class="clearfix">
                                    <div class="form-group formcom" style="width:58%;">
                                        <label class="col-sm-5 control-label" style="margin-left:-5px;">排序：</label>
                                        <div class="col-sm-7">
                                            <input type="text" class="form-control" name="orderno" placeholder="请输入排序">
                                        </div>
                                    </div>
                                    <div class="form-group   formcom" style="width:42%;">
                                        <label class="col-sm-5 control-label">启用否：</label>
                                        <div class="col-sm-7">
                                            <select class="editEnabledPicker selectpicker" name="status">
                                                <option value="1" selected>启用</option>
                                                <option value="0">停用</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-sm-3 control-label">备注：</label>
                                    <div class="col-sm-9">
                                        <textarea class="form-control" name="description"
                                                  placeholder="请输入内容"></textarea>
                                    </div>
                                </div>
                                <!--由授权功能替换-->
                                <!--<div class="form-group" id="editRelationDiv">
                                    <label class="col-sm-3 control-label">选择坐席组：</label>
                                    <div class="col-sm-9">
                                        <div class="rrow clearfix" id="editRelationListDiv">
                                            &lt;!&ndash;"<div class='ritem'><input type='checkbox' name='seatGroupList' value='" + seat.id + "'/><span>" + seat.name + "</span></div>"&ndash;&gt;
                                        </div>
                                    </div>
                                </div>-->
                                <button type="reset" id="eidtResetBtn" hidden>重置</button>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="savebtn btn btn-primary" id="editSaveBtn">保存</button>
                            <button type="button" class="cancelbtn btn btn-default" data-dismiss="modal">取消</button>
                        </div>
                    </div>
                </div>
            </div>
            <!--删除机构时 机构下有人 确认modal -->
            <div class="modal fade" id="hasUerModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
                 data-backdrop=false>
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                    aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title">删除</h4>
                        </div>
                        <div class="modal-body">
                            <p>该机构下有用户，是否删除？</p>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="csavebtn btn btn-primary">确定</button>
                            <button type="button" class="cancelbtn btn btn-default" data-dismiss="modal">取消</button>
                        </div>
                    </div>
                </div>
            </div>
            <!--确定 modal -->
            <div class="modal fade" id="confirmDeleteModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
                 data-backdrop=false>
                <div class="modal-dialog" role="document">
                    <input type="hidden" id="deleteId" value=""/>
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                    aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title">删除</h4>
                        </div>
                        <div class="modal-body">
                            <p>确定要操作吗？</p>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="csavebtn btn btn-primary">确定</button>
                            <button type="button" class="cancelbtn btn btn-default" data-dismiss="modal">取消</button>
                        </div>
                    </div>
                </div>
            </div>
            <!--停用机构时 机构下有人 确认modal -->
            <div class="modal fade" id="hasUerModal2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
                 data-backdrop=false>
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <input type="hidden" id="stopId" value=""/>
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                    aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title">停用</h4>
                        </div>
                        <div class="modal-body">
                            <p>选中的机构下有用户，是否停用？</p>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="csavebtn btn btn-primary">确定</button>
                            <button type="button" class="cancelbtn btn btn-default" data-dismiss="modal">取消</button>
                        </div>
                    </div>
                </div>
            </div>
            <!--停用机构时 机构下有人 确认modal -->
            <div class="modal fade" id="confirmStopModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
                 data-backdrop=false>
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                    aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title">停用</h4>
                        </div>
                        <div class="modal-body">
                            <p>确定要操作吗？</p>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="csavebtn btn btn-primary">确定</button>
                            <button type="button" class="cancelbtn btn btn-default" data-dismiss="modal">取消</button>
                        </div>
                    </div>
                </div>
            </div>
            <!--导入 modal -->
            <div class="modal fade" id="importModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
                 data-backdrop=false>
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                    aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title">
                                导入
                            </h4>
                        </div>
                        <div class="modal-body">
                            <form class="form-horizontal" role="form" id="importForm">
                                <div class="form-group">
                                    <label class="col-sm-4 control-label">所属省份：</label>
                                    <div class="col-sm-7">
                                        <select class="resourceTypepicker selectpicker" name="areaid">
                                        </select>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-sm-4 control-label"><span class="respan">*</span>上传：</label>
                                    <div class="col-sm-7" id="uploadDiv">
                                        <!--<div class="file-loading">
                                            <input id="uploadFile" name="uploadFile" type="file" />
                                        </div>
                                        <div id="errorBlock" class="help-block"></div>-->
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-sm-4 control-label"></label>
                                    <div class="col-sm-7">
                                        <button type="button" class="btn btn-outline btn-default"
                                                onclick="window.location.href=basePath+'app/template/组织机构批量导入模板.xls';">
                                            点击获取模板文件
                                        </button>
                                        <div>
                                            <ul class="importTips">
                                                <li><span>●</span>不选省份则默认导入到集团中。</li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="csavebtn btn btn-primary" id="importConfirmBtn">确定</button>
                            <button type="button" class="cancelbtn btn btn-default" data-dismiss="modal">取消</button>
                        </div>
                    </div>
                </div>
            </div>
            <!--删除-->
            <div class="modal fade" id="powerModal" tabindex="-1" role="dialog" aria-labelledby="myModalP"
                 data-backdrop=false>
                <div class="modal-dialog" role="document" style="width:600px;">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                    aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title" id="myModalP">授权</h4>
                        </div>
                        <div class="modal-body" style="overflow: hidden;padding:15px 20px 20px 20px;">
                            <div class="powerLeft">
                                <h4>未授权</h4>
                                <div class="boxP">
                                    <div class="search_box">
                                        <input type="text" style="width: 172px;padding:1px 5px;"
                                               autocomplete="off"><span class="fa fa-search fa_btn"></span>
                                    </div>
                                    <div id="jstreeL" class="scrollbar">

                                    </div>
                                </div>
                            </div>
                            <div class="powerMiddle">
                                <button class="fa fa-hand-o-right" title="授权" id="authon"></button>
                                <button class="fa fa-hand-o-left" title="撤销" id="unAuthon"></button>
                            </div>
                            <div class="powerRight">
                                <h4>已授权</h4>
                                <div class="boxP">
                                    <div class="search_box">
                                        <input type="text" style="width: 172px;padding:1px 5px;"
                                               autocomplete="off"><span class="fa fa-search fa_btn"></span>
                                    </div>
                                    <div id="jstreeR" class="scrollbar">

                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<a id="basePath" th:href="@{/}"></a>
<script src="../../../assert/js/jquery.js" th:src="@{/assert/js/jquery.js(v_=${@commonController.getSysConfigByPK('CACHE_CODE')})}"></script>
<script src="../../../assert/js/bootstrap.min.js" th:src="@{/assert/js/bootstrap.min.js(v_=${@commonController.getSysConfigByPK('CACHE_CODE')})}"></script>
<script src="../../../assert/js/plugin/bootstrap-table/bootstrap-table.min.js"
        th:src="@{/assert/js/plugin/bootstrap-table/bootstrap-table.min.js(v_=${@commonController.getSysConfigByPK('CACHE_CODE')})}"></script>
<script src="../../../assert/js/plugin/bootstrap-table/bootstrap-table-mobile.min.js"
        th:src="@{/assert/js/plugin/bootstrap-table/bootstrap-table-mobile.min.js}"></script>
<script src="../../../assert/js/plugin/bootstrap-table/locale/bootstrap-table-zh-CN.min.js"
        th:src="@{/assert/js/plugin/bootstrap-table/locale/bootstrap-table-zh-CN.min.js}"></script>
<script src="../../../assert/js/bootstrap-select.js" th:src="@{/assert/js/bootstrap-select.js}"></script>
<script src="../../../assert/js/bootstrapValidator.js" th:src="@{/assert/js/bootstrapValidator.js}"></script>
<script src="../../../assert/js/base.js"
        th:src="@{/assert/js/base.js(v_=${@commonController.getSysConfigByPK('CACHE_CODE')})}"></script>
<script src="../../../assert/js/common.js"
        th:src="@{/assert/js/common.js(v_=${@commonController.getSysConfigByPK('CACHE_CODE')})}"></script>
<script src="../../../assert/js/toastr.min.js" th:src="@{/assert/js/toastr.min.js}"></script>
<script src="../../../assert/js/plugin/jsTree/jstree.min.js"
        th:src="@{/assert/js/plugin/jsTree/jstree.min.js}"></script>
<script src="../../../assert/js/bootstrap-fileinput/js/fileinput.min.js"
        th:src="@{/assert/js/bootstrap-fileinput/js/fileinput.min.js}"></script>
<script src="../../../assert/js/bootstrap-fileinput/js/locales/zh.js"
        th:src="@{/assert/js/bootstrap-fileinput/js/locales/zh.js}"></script>
<script src="../../../assert/js/plugin/chosen/chosen.jquery.js"
        th:src="@{/assert/js/plugin/chosen/chosen.jquery.js}"></script>
<script type="text/javascript">
    //项目名称
    var basePath = $("#basePath").attr("href");
    //    判断是否是集团人员
    var userIdentity = $("#userIdentity", parent.document).text();
    // 获取所有组织机构类型
    var groupTypeList;
    $.ajax({
        type: "GET",
        async: false,
        url: basePath + "rest/statusAtt/statusAttsGetByType?type=sys_group_type",
        success: function (data) {
            groupTypeList = data;
        }
    });
    // 加载表格
    var TableInit = function () {
        var oTableInit = new Object();
        //初始化Table
        oTableInit.Init = function () {
            $("#groupTable").bootstrapTable('destroy');
            $('#groupTable').bootstrapTable({
                url: basePath + "rest/group/groupsByPage", //请求后台的URL（*）
                method: "get", //请求方式（*）
                dataType: "json",
                contentType: "application/x-www-form-urlencoded;charset=UTF-8",
                dataField: "rows", //服务端返回数据键值 就是说记录放的键值是rows，分页时使用总记录数的键值为total
                totalField: "total",
                striped: true, //是否显示行间隔色
                cache: false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                pagination: true, //是否显示分页（*）
                sortable: true, //是否启用排序
                sortName: "id", //排序方式
                sortOrder: "asc", //排序方式
                clickToSelect: true,
                queryParams: oTableInit.queryParams, //传递参数（*）
                queryParamsType: "", //  queryParamsType = 'limit' 参数: limit, offset, search, sort, order;
                sidePagination: "server", //分页方式：client客户端分页，server服务端分页（*）
                pageNumber: 1, //初始化加载第一页，默认第一页
                pageSize: 10, //每页的记录行数（*）
                pageList: [10, 15, 20, 25], //可供选择的每页的行数（*）
                idField: "id",
                uniqueId: "id", //每一行的唯一标识，一般为主键列
                columns: [{
                    field: 'id',
                    title: 'ID',
                    sortable: true,
                    visible: false
                }, {
                    field: 'checkStatus',
                    title: '全选',
                    checkbox: true
                }, {
                    field: 'areaname',
                    title: '省份',
                    sortable: true
                }, {
                    field: 'parentname',
                    title: '所属组织机构',
                    sortable: true
                }, {
                    field: 'name',
                    title: '名称',
                    sortable: true
                }, {
                    field: 'type',
                    title: '机构类型',
                    sortable: true,
                    formatter: function (value, row, index) {
                        var name = '';
                        $.each(groupTypeList, function (i, e) {
                            if (e.value == value) {
                                name = e.name;
                            }
                        });
                        return name;
                    }
                }, {
                    field: 'status',
                    title: '状态',
                    sortable: true,
                    formatter: function (value, row, index) {
                        if (value == "0") return "停用";
                        else return "启用";
                    }
                }, {
                    field: 'description',
                    title: '备注',
                    width: 200,
                    sortable: false,
                    formatter: function (value, row, index) {
                        if (value == null) {
                            value = ""
                        }
                        return "<div class='onoteBoxTable' title='" + value + "'>" + value + "</div>";
                    }

                }],
                formatLoadingMessage: function () {
                    return "请稍等，正在加载中...";
                },
                formatNoMatches: function () { //没有匹配的结果
                    return '无符合条件的记录';
                },
                onLoadSuccess: function (data) {  //加载成功时执行
                    resize.me();
                },
                onLoadError: function (data) {
                    $('#groupTable').bootstrapTable('removeAll');
                },
                responseHandler: function (res) {
                    return {
                        total: res.totalCount,
                        rows: res.result
                    };
                }
            });
        };
        //得到查询的参数
        oTableInit.queryParams = function (params) {
            // 获取左侧选中的节点 通过节点来判断传入后台的是省份id还是机构id
            var nodeIdArray = $("#organizTree").jstree("get_selected");
            var areaId = null, groupId = null;
            if (nodeIdArray.length > 0) {
                // 树只有一个选中节点 机构节点id为正 省份节点id为负
                var nodeId = nodeIdArray[0];
                if (nodeId > 0) groupId = nodeId;
                else areaId = Math.abs(nodeId);
            }
            var temp = { //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
                "pageSize": params.pageSize,
                "pageNum": params.pageNumber,
                "sortName": this.sortName,
                "sortOrder": this.sortOrder,
                "status": $("#statusSearch").val() != null ? $("#statusSearch").val().join(",") : null,
                "type": $("#mechanismType").val() != null ? $("#mechanismType").val().join(",") : null,
                "name": $.trim($("#nameSearch").val()),
                "areaId": areaId,
                "groupId": groupId
            };
            return temp;
        };
        return oTableInit;
    };

    // 添加组织机构
    var groupAddFun = {
        init: function () {
            groupAddFun.formInit();
            groupAddFun.showAddTree();
            groupAddFun.typeChange();
            groupAddFun.save();
        },
        formInit: function () {
            // 初始化表单
            $("#groupModal").on("show.bs.modal", function () {
                // 初始化 组织机构选中modal
                $("#addResetBtn").click();
                // 从数据库读取省份信息
                $.ajax({
                    type: "post",
                    url: basePath + "rest/area/showAllAreas",
                    async: false,
                    success: function (data) {
                        if (data != null) {
                            $.get(basePath + "rest/area/getAreaInfo", function (areaInfo) {
                                if (areaInfo == null || areaInfo == "") {
                                    // 说明为超管或者集团人员 页面上要多一个请选择选项
                                    $('#groupForm :input[name="areaid"]').html("").append("<option value='' selected>请选择</option>");
                                }
                                $.each(data, function (index, area) {
                                    $('#groupForm :input[name="areaid"]').append("<option value='" + area.id + "'>" + area.area + "</option>");
                                });
                                $('#groupForm :input[name="areaid"]').selectpicker('refresh');
                                // 树的初始话必须在省份下拉框初始话成功之后
                                groupAddFun.addTreeInit();
                            });
                        }
                    }
                });
                $('#groupForm :input[name="status"]').selectpicker('val', 1);
                $("#groupForm :input[name='type']").selectpicker('val', 2);
                // 每次打开模态框的时候重新加载一次树 保证新增机构之后树的数据也会更新
                $("#groupForm input[name='parentid']").val("");
                /*【由授权功能替换】// 初始化坐席组信息-清空坐席列表
                 qcRelationFun.addInit();*/
            });
        },
        showAddTree: function () {
            $("#groupForm input[name='parentname']").off("click").on("click", function () {
                // 允许省份为空 不校验
                //var areaId = $('#groupForm :input[name="areaid"] option:selected').val();
                //var areaName = $('#groupForm :input[name="areaid"] option:selected').text();
                // 显示树
                $("#addTree").css("display", "block");
            });
        },
        typeChange: function () {
            //groupAddFun.addTreeInit();
            // 给组织机构类型选择绑定事件
            $("#groupForm :input[name='type']").off("change").on("change", function () {
                var type = $(this).selectpicker("val");
                var areaId = $('#groupForm :input[name="areaid"]').val();
                var parentId = $('#groupForm input[name="parentid"]').val();
                // 未设置所属机构时 不能添加坐席或者质检组
                // if (parentId == "" && type != "2") {
                //     toastr.error("质检组或者坐席组必须先设置所属组织机构");
                //     $(this).selectpicker("val", "2");
                //     return false;
                // }
                // 增加判断：当所属机构名称中含有质检或者坐席的时候 添加的机构类型也跟所属机构一样
                var parentName = $('#groupForm input[name="parentname"]').val();
                if (parentName.indexOf("质检") != -1 && type == "0") {
                    toastr.error("质检机构下不可添加坐席组");
                    $(this).selectpicker("val", "1");
                    return false;
                }
                if (parentName.indexOf("坐席") != -1 && type == "1") {
                    toastr.error("坐席机构下不可添加质检组");
                    $(this).selectpicker("val", "0");
                    return false;
                }
                // 如果校验通过则刷新下下拉框
                $(this).selectpicker('refresh');
                /* 【由授权功能替换】
                 // 检验通过了 如果添加的是质检组 则显示可选择坐席组
                 if (type == 1 && areaId != "") {
                 groupAddFun.showSeatGroup(areaId);
                 } else {
                 qcRelationFun.addInit();
                 }*/
            });
            // 给省份选择绑定事件
            $("#groupForm :input[name='areaid']").off("change").on("change", function () {
                /* 【由授权功能替换】
                 // 坐席组初始化
                 var areaId = $(this).val();
                 var type = $('#groupForm :input[name="type"]').val();
                 if (type == 1 && areaId != "") {
                 groupAddFun.showSeatGroup(areaId);
                 } else {
                 qcRelationFun.addInit();
                 }*/
                // 如果省份变更 所属组织机构需要同时变更
                $("#groupForm input[name='parentid']").val("");
                $("#groupForm input[name='parentname']").val("");
                // 对树进行初始化
                groupAddFun.addTreeInit();
            });
        },
        addTreeInit: function () {
            var areaId = $('#groupForm :input[name="areaid"] option:selected').val();
            // 树初始化
            $('#addTree').jstree("destroy");
            $('#addTree').data('jstree', false).empty();
            $("#addTree").jstree({
                "core": {
                    "animation": false,
                    "multiple": false,
                    "check_callback": true,
                    'data': function (obj, callback) {
                        $.ajax({
                            type: "GET",
                            url: basePath + 'rest/group/showAddTree?areaId=' + areaId,
                            async: false,
                            success: function (result) {
                                if (result != null) {
                                    var arr = [];
                                    arr.push(result);
                                    callback.call(this, orgTree.loopMenu(arr, true));
                                }
                            }
                        });
                    }
                },
                "types": {
                    "default": {
                        "icon": "jstree-folder"
                    },
                    "html": {
                        "icon": "jstree-file"
                    }
                },
                "plugins": ["types", "search", "unique"]
            }).on("loaded.jstree", function (e, data) {
                // 初始化选择项
                var instance = data.instance;
                // 获取已选中的菜单项
                var groupId = $("#groupForm input[name='parentid']").val();
                instance.select_node(groupId);
            });
            // 隐藏树
            $('#addTree').on("changed.jstree", function (e, data) {
                var groupId = data.selected;
                if (groupId > 0) {
                    $("#groupForm input[name='parentid']").val(groupId);
                    $("#groupForm input[name='parentname']").val(data.instance.get_selected(true)[0].text);
                } else {
                    $("#groupForm input[name='parentid']").val("");
                    $("#groupForm input[name='parentname']").val("");
                }
                $("#addTree").css("display", "none");
            });
        },
        /* 【由授权功能替换】
         showSeatGroup: function (areaId) {
         //根据省份id获取该省份下坐席组信息
         $.ajax({
         type: "post",
         url: basePath + "rest/group/selectSeatGroup",
         data: {areaId: areaId},
         success: function (data) {
         // 页面展示坐席组信息
         $("#addRelationListDiv").html("");
         if (data.length > 0) {
         $.each(data, function (index, seatGroup) {
         $("#addRelationListDiv").append("<div class='ritem'><input type='checkbox' name='seatgroupidlist' value='" + seatGroup.id + "'/><span>" + seatGroup.name + "</span></div>");
         });
         } else {
         $("#addRelationListDiv").append("<span>坐席组未添加</span>");
         }
         $("#addRelationDiv").css("display", "block");
         }
         });
         },*/
        save: function () {
            $("#addSaveBtn").off("click").on("click", function () {
                var bv = $('#groupForm').data('bootstrapValidator');
                bv.validate();
                if (bv.isValid()) {
                    // 表单提交前移除disabled属性 当时某个省份登录时 只有一个选项 所以没有禁用了
                    // $('#groupForm :input[name="areaid"]').removeAttr("disabled");
                    $.ajax({
                        type: "post",
                        url: basePath + "rest/group/groupAdd",
                        data: $("#groupForm").serialize(),
                        success: function (data) {
                            if (data.type == "success") {
                                $("#groupModal").modal("hide");
                                $("#groupTable").bootstrapTable("refresh");
                                toastr.success("组织机构添加成功");
                                $("#organizTree").jstree("refresh");
                            } else if (data.type == "warning") {
                                toastr.warning(data.message);
                            } else {
                                toastr.error(data.message);
                            }
                        }
                    });
                }
            });
        }
    };

    // 修改组织机构
    var groupEditFun = {
        init: function () {
            groupEditFun.openEditModal();
            groupEditFun.formInit();
            groupEditFun.typeChange();
            groupEditFun.showEditTree();
            groupEditFun.save();
        },
        openEditModal: function () {
            $("#editBtn").off("click").on("click", function () {
                var rows = $("#groupTable").bootstrapTable("getSelections");
                if (rows.length == 0) {
                    toastr.error('请选择行');
                } else if (rows.length > 1) {
                    toastr.error('单次只能选择一行进行修改');
                } else {
                    var groupId = rows[0].id;
                    $("#groupId").val(groupId);
                    $("#editGroupModal").modal("show");
                }
            });
        },
        formInit: function () {
            // 初始化表单
            $("#editGroupModal").on("show.bs.modal", function () {
                // 从数据库读取省份信息
                $.ajax({
                    type: "post",
                    url: basePath + "rest/area/showAllAreas",
                    async: false,
                    success: function (data) {
                        $('#editGroupForm :input[name="areaid"]').html("");
                        if (data != null) {
                            $.each(data, function (index, area) {
                                $('#editGroupForm :input[name="areaid"]').append("<option value='" + area.id + "'>" + area.area + "</option>");
                            });
                            $('#editGroupForm :input[name="areaid"]').selectpicker('refresh');
                        }
                    }
                });
                // 初始化表单值
                $.ajax({
                    type: "post",
                    url: basePath + "rest/group/groupGetByPK",
                    data: {id: $("#groupId").val()},
                    success: function (data) {
                        if (data != null) {
                            // 省份不允许修改
                            var $select = $('#editGroupForm :input[name="areaid"]');
                            if (data.areaid == 9999) {
                                $select.html("").append("<option value=''>集团</option>").attr("disabled", "disabled");
                            } else {
                                $select.selectpicker('val', data.areaid);
                                $select.attr("disabled", "disabled");
                            }
                            $select.selectpicker("refresh");
                            $("#editGroupModal input[name='parentid']").val(data.parentid).attr("oldvalue", data.parentid);
                            $("#editGroupModal input[name='parentname']").val(data.parentname);
                            $("#editGroupModal input[name='name']").val(data.name).attr("oldvalue", data.name);
                            $("#editGroupModal input[name='orderno']").val(data.orderno);
                            $("#editGroupModal :input[name='description']").val(data.description);
                            $("#editGroupModal :input[name='type']").selectpicker('val', data.type); // 在type初始化时 坐席组信息会关联初始化
                            if (data.type != 2) {
                                // 如果为质检组或坐席组 则不允许再修改
                                $("#editGroupModal :input[name='type']").attr("disabled", "disabled").selectpicker("refresh");
                            } else {
                                // 当当前修改的机构有下级时 也不允许修改机构类型
                                var groupId = $("#groupId").val();
                                $.ajax({
                                    type: "GET",
                                    async: false,
                                    url: basePath + "/rest/group/checkSubGroupNum?groupId=" + groupId,
                                    success: function (data) {
                                        if (data > 0) {
                                            $("#editGroupModal :input[name='type']").attr("disabled", "disabled").selectpicker("refresh");
                                        } else {
                                            $("#editGroupModal :input[name='type']").removeAttr("disabled").selectpicker("refresh");
                                        }
                                    }
                                });
                            }
                            $("#editGroupModal :input[name='status']").selectpicker('val', data.status);
                            // 机构树初始化
                            groupEditFun.editTreeInit();
                        }
                    }
                });
            });
        },
        /* 【由授权功能替换】
         seatGroupInit: function (areaId, groupId) {
         // 初始化坐席组信息
         $.ajax({
         type: "post",
         url: basePath + "rest/group/selectSeatGroup",
         data: {areaId: areaId},
         success: function (data) {
         // 页面展示坐席组信息
         $("#editRelationListDiv").html("");
         if (data.length > 0) {
         $.each(data, function (index, seatGroup) {
         $("#editRelationListDiv").append("<div class='ritem'><input type='checkbox' name='seatgroupidlist' value='" + seatGroup.id + "'/><span>" + seatGroup.name + "</span></div>");
         });
         // 获取已经选中的坐席组信息
         $.ajax({
         type: "post",
         url: basePath + "rest/group/selectedSeat",
         data: {qcGroupId: groupId},
         success: function (qcRelation) {
         if (undefined != qcRelation.seatGroupIdList) {
         var seatGroupIdList = qcRelation.seatGroupIdList;
         if (seatGroupIdList.length > 0) {
         $.each(seatGroupIdList, function (index, seatGroupId) {
         $("#editRelationListDiv :checkbox[value='" + seatGroupId + "']").prop("checked", true);
         });
         }
         }
         }
         });
         } else {
         $("#editRelationListDiv").append("<span>坐席组未添加</span>");
         }
         $("#editRelationDiv").css("display", "block");
         }
         });
         },*/
        typeChange: function () {
            // 给组织机构类型选择绑定事件
            $("#editGroupForm :input[name='type']").off("change").on("change", function () {
                var type = $(this).selectpicker("val");
                var parentId = $('#editGroupForm input[name="parentid"]').val();
                // 未设置所属机构时 不能添加坐席或者质检组
                // if (parentId == "" && type != "2") {
                //     toastr.error("质检组或者坐席组必须先设置所属组织机构");
                //     $(this).selectpicker("val", "2");
                //     return false;
                // }
                // 如果校验通过则刷新下下拉框
                $(this).selectpicker('refresh');
                /* 【由授权功能替换】
                 if (type == 1 && areaId != "") {
                 var groupId = $("#groupId").val();
                 groupEditFun.seatGroupInit(areaId, groupId);
                 } else {
                 qcRelationFun.editInit();
                 }*/
            });
        },
        editTreeInit: function () {
            // 当前组织机构所属上级组织机构id
            var areaId = $('#editGroupForm :input[name="areaid"] option:selected').val();
            /* 因为有集团 areaId也可以为空了
             // 如果省份没有选中 也不允许修改树结构
             if (areaId == "") {
             return false;
             }*/
            // 树初始化
            $('#editTree').jstree("destroy");
            $('#editTree').data('jstree', false).empty();
            $("#editTree").jstree({
                "core": {
                    "animation": false,
                    "multiple": false,
                    "check_callback": true,
                    'data': function (obj, callback) {
                        $.ajax({
                            type: "get",
                            url: basePath + 'rest/group/showEditTree?areaId=' + areaId + "&groupId=" + $("#groupId").val(),
                            async: false,
                            success: function (result) {
                                if (result != null) {
                                    var arr = [];
                                    arr.push(result);
                                    callback.call(this, orgTree.loopMenu(arr, true));
                                }
                            }
                        });
                    }
                },
                "types": {
                    "default": {
                        "icon": "jstree-folder"
                    },
                    "html": {
                        "icon": "jstree-file"
                    }
                },
                "plugins": ["types", "search", "unique"]
            }).on("loaded.jstree", function (e, data) {
                // 初始化选择项
                var instance = data.instance;
                // 获取已选中的菜单项
                var parentId = $('#editGroupForm input[name="parentid"]').val();
                instance.select_node(parentId);
            });
            // 隐藏树
            $('#editTree').on("changed.jstree", function (e, data) {
                // 判断当前修改的机构类型 避免出现坐席或质检组所属机构为空
                var type = $("#editGroupModal :input[name='type']").val();
                if (type == 0 || type == 1) {
                    if (data.selected < 0) {
                        var parentId = $("#editGroupModal input[name='parentid']").val();
                        data.instance.deselect_all();
                        data.instance.select_node(parentId);
                        toastrCog.error("不能修改坐席或质检组所属机构为空");
                        return;
                    }
                }
                if (data.selected > 0) {
                    $("#editGroupModal input[name='parentid']").val(data.selected);
                    $("#editGroupModal input[name='parentname']").val(data.instance.get_selected(true)[0].text);
                } else {
                    $("#editGroupModal input[name='parentid']").val("");
                    $("#editGroupModal input[name='parentname']").val("");
                }
                $("#editTree").css("display", "none");
            });
        },
        showEditTree: function () {
            $("#editGroupModal input[name='parentname']").off("click").on("click", function () {
                // 当前组织机构所属上级组织机构id
                // var parentId = $("#editGroupModal input[name='parentid']").attr("oldvalue");
                $("#editTree").css("display", "block");
            });
        },
        save: function () {
            $("#editSaveBtn").off("click").on("click", function () {
                var bv = $('#editGroupForm').data('bootstrapValidator');
                bv.validate();
                if (bv.isValid()) {
                    // 表单提交前移除disabled属性
                    $('#editGroupForm :input[name="areaid"]').removeAttr("disabled");
                    $.ajax({
                        type: "post",
                        url: basePath + "rest/group/groupUpdate",
                        data: $("#editGroupModal form").serialize(),
                        success: function (data) {
                            if (data.type == "success") {
                                $("#editGroupModal").modal("hide");
                                $("#groupTable").bootstrapTable("refresh");
                                toastr.success("组织机构修改成功");
                                $("#organizTree").jstree("refresh");
                            } else {
                                toastr.error("组织机构修改失败");
                            }
                        }
                    });
                }
            });
        }
    };

    // 状态修改
    var groupStatusChangeFun = {
        init: function () {
            groupStatusChangeFun.batchOn();
            groupStatusChangeFun.batchOff();
            groupStatusChangeFun.confirm();
        },
        batchOn: function () {
            // 批量启用按钮事件绑定
            $("#batchOnBtn").off("click").on("click", function () {
                groupStatusChangeFun.batch(1);
            });
        },
        batchOff: function () {
            // 批量停用按钮事件绑定
            $("#batchOffBtn").off("click").on("click", function () {
                groupStatusChangeFun.batch(0);
            });
        },
        batch: function (status) {
            // 先获取要启用或停用的组织机构id
            var rows = $("#groupTable").bootstrapTable("getSelections");
            if (rows.length == 0) {
                toastr.error('请至少选择一条组织机构信息');
            } else {
                var idList = [];
                var statusStr = "";
                $.each(rows, function (index, row) {
                    idList.push(row.id);
                    statusStr += row.status;
                });
                if (statusStr.indexOf(status) > -1) {
                    var str = "";
                    if (status == 1) {
                        str = "启用"
                    } else {
                        str = "停用"
                    }
                    toastr.error('包含已' + str + "组织结构！");
                    return
                }
                // 当停用的时候 判断机构里面是不是有人
                $("#stopId").val(idList.join(","));
                if (status == 0) {
                    $.get(basePath + "rest/group/countUserInGroups?idList=" + idList.join(","), function (data) {
                        if (data > 0) {
                            // 如果大于0 提示机构下有人
                            $("#hasUerModal2").modal("show");
                        } else {
                            // 提示是否删除
                            $("#confirmStopModal").modal("show");
                        }
                    })
                } else {
                    // 直接修改状态
                    groupStatusChangeFun.operation(idList, status);
                }
            }
        },
        confirm: function () {
            // 在删除模态框中点击确定时触发的删除事件绑定
            $("#hasUerModal2 .csavebtn").off("click").on("click", function () {
                $("#hasUerModal2").modal("hide");
                $("#confirmStopModal").modal("show");
            });
            // 在删除模态框中点击确定时触发的删除事件绑定
            $("#confirmStopModal .csavebtn").off("click").on("click", function () {
                $("#confirmStopModal").modal("hide");
                var idList = $("#stopId").val();
                groupStatusChangeFun.operation(idList, 0);
            });
        },
        operation: function (idList, status) {
            // 批量操作
            $.ajax({
                type: "post",
                url: basePath + "rest/group/statusBatch",
                data: {idList: idList, status: status},
                traditional: true,
                success: function (data) {
                    if (data.type == "success") {
                        toastr.success("组织机构批量修改成功");
                        $("#organizTree").jstree("refresh");
                        $("#groupTable").bootstrapTable("refresh");
                    } else {
                        toastr.error("组织机构批量修改失败");
                    }
                }
            });
        }
    };

    // 组织机构删除
    var groupDeleteFun = {
        init: function () {
            groupDeleteFun.batch();
            groupDeleteFun.confimDelete();
        },
        batch: function () {
            // 批量删除按钮事件绑定
            $("#batchDeleteBtn").off("click").on("click", function () {
                // 初始化要删除的id值
                $("#deleteId").val("");
                // 先获取选中的行
                var rows = $("#groupTable").bootstrapTable("getSelections");
                if (rows.length == 0) {
                    toastr.error('请选择行');
                } else {
                    var ids = [];
                    var isCanDelete = true;
                    $.each(rows, function (index, row) {
                        if (row.status == 1) {
                            isCanDelete = false;
                        }
                        ids.push(row.id);
                    });
                    if (!isCanDelete) {
                        // 修改为模态框弹出
                        toastrCog.error("选中的机构为启用状态，不允许删除", 2000);
                        return false;
                    }
                    $("#deleteId").val(ids.join(","));
                    $.get(basePath + "rest/group/countUserInGroups?idList=" + ids.join(","), function (data) {
                        if (data > 0) {
                            // 如果大于0 说明机构下有人 提示是否进行删除
                            $("#hasUerModal").modal("show");
                        } else {
                            // 弹出删除确认模态框
                            $("#confirmDeleteModal").modal("show");
                        }
                    })
                }
            });
        },
        confimDelete: function () {
            // 在删除模态框中点击确定时触发的删除事件绑定
            $("#confirmDeleteModal .csavebtn").off("click").on("click", function () {
                var idList = $("#deleteId").val().split(",");
                $.ajax({
                    type: "post",
                    url: basePath + "rest/group/groupDeleteBatch",
                    data: {idList: idList},
                    traditional: true,
                    success: function (data) {
                        // 相应后关闭model框
                        $("#confirmDeleteModal").modal("hide");
                        if (data.type == "success") {
                            toastr.success('删除成功');
                            $("#organizTree").jstree("refresh");
                        } else {
                            toastr.error('删除失败');
                        }
                        // 刷新表格
                        $("#groupTable").bootstrapTable("refresh");
                    }
                });
            });
            // 在删除模态框中点击确定时触发的删除事件绑定
            $("#hasUerModal .csavebtn").off("click").on("click", function () {
                $("#hasUerModal").modal("hide");
                $("#confirmDeleteModal").modal("show");
            });
        }
    };

    // 基础功能
    var baseFun = {
        init: function () {
            baseFun.search();
            baseFun.reset();
        },
        // 点击搜索时表格重新加载
        search: function () {
            // 点击搜索 刷新查询table
            $("#searchBtn").off("click").on("click", function () {
                $("#groupTable").bootstrapTable('refreshOptions', {pageNumber: 1});
                $("#groupTable").bootstrapTable('refresh');
            });
            $("body").on("keyup", function (e) {
                var code = e.charCode || e.keyCode;
                if (code == 13) {
                    //此处编写用户敲回车后的代码
                    $("#groupTable").bootstrapTable('refreshOptions', {pageNumber: 1});
                    $("#groupTable").bootstrapTable('refresh');
                }
            })
        },
        reset: function () {
            $("#reset").on("click", function () {
                bs.resetSearch($(".cquery"));
                $("#statusSearch").selectpicker("val", "");
                $("#statusSearch").selectpicker("refresh");
                $("#groupTable").bootstrapTable('refreshOptions', {pageNumber: 1});
                $("#groupTable").bootstrapTable('refresh');
            })
        }
    };

    // 校验相关
    var validateFun = {
        init: function () {
            this.initKeyValidator();
            this.initOpen();
        },
        initKeyValidator: function () {

            var option = {
                live: "enabled",
                message: 'This value is not valid',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
//                    areaid: {
//                        validators: {
//                            notEmpty: {
//                                message: '所属省份不能为空'
//                            }
//                        }
//                    },
//                     parentname: {
//                         validators: {
//                             callback: {
//                                 message: '所属组织机构不能为空',
//                                 callback: function (value, validator, $field) {
//                                     // 当登录用户为集团用户时允许为空 否则不允许为空
//                                     var isGroupCanBeNull = false;
//                                     $.ajax({
//                                         type: "post",
//                                         async: false,
//                                         url: basePath + "rest/users/isGroupCanBeNull",
//                                         success: function (data) {
//                                             if (data == "yes") {
//                                                 isGroupCanBeNull = true;
//                                             }
//                                         }
//                                     });
//                                     if (!isGroupCanBeNull && value == "") {
//                                         return false;
//                                     }
//                                     return true;
//                                 }
//                             }
//                         }
//                     },

                    orderno: {
                        trigger: "change",
                        validators: {
                            /*notEmpty: {
                             message: '排序不能为空'
                             },*/
                            regexp: { //正则表达式
                                regexp: /^\+?[1-9][0-9]*$/,
                                message: '请输入大于等于0的整数',
                            },

                        }
                    },
                    name: {
                        trigger: "change",//关键配置
                        validators: {
                            notEmpty: {
                                message: '名称不能为空'
                            },
                            stringLength: {
                                max: 20,
                                message: '长度不允许超过20个字符'
                            },
                            callback: {
                                message: '该名称已存在',
                                callback: function (value, validator, $field) {
                                    // 如果oldvalue与当前值一样 说明操作为修改机构名称且名称尚未修改
                                    if (value == $field.attr("oldvalue")) {
                                        return true;
                                    }
                                    var isExist = false;
                                    var areaId = $field.parent().parent().parent().parent().find("select[name='areaid']").selectpicker('val');
                                    if (areaId != '') {
                                        $.ajax({
                                            type: "get",
                                            async: false,
                                            url: basePath + "rest/group/nameUniqueCheck",
                                            data: {name: value, areaId: areaId},
                                            success: function (data) {
                                                if (data.type == "success") {
                                                    isExist = true;
                                                }
                                            }
                                        });
                                    } else {
                                        // 没有选择省份 先不做校验
                                        isExist = true;
                                    }
                                    return isExist;
                                }
                            }
                        }
                    }
                }
            };
            $('#groupForm').bootstrapValidator(option);
            $('#editGroupForm').bootstrapValidator(option);
        },
        initOpen: function () {
            $("#groupModal").on("hide.bs.modal", function () {
                $('#groupForm').data('bootstrapValidator').resetForm(true);
            });

            $("#editGroupModal").on("hide.bs.modal", function () {
                $('#editGroupForm').data('bootstrapValidator').resetForm(true);
            });
        }
    };

    //所属组织结构
    var orgTree = {
        init: function () {
            orgTree.render();
        },
        render: function (tree) {
            $("#organizTree").jstree({
                "core": {
                    "animation": false,
                    "multiple": false,
                    "check_callback": true,
                    'data': function (obj, callback) {
                        $.ajax({
                            type: "GET",
                            url: basePath + 'rest/group/showGroupTree',
                            dataType: "json",
                            async: false,
                            success: function (result) {
                                if (result != null) {
                                    if (result.constructor === Array) {
                                        callback.call(this, orgTree.loopMenu(result));
                                    } else {
                                        var arr = [];
                                        arr.push(result);
                                        callback.call(this, orgTree.loopMenu(arr));
                                    }
                                }
                            }
                        });
                    }
                },
                "types": {
                    "default": {
                        "icon": "jstree-folder"
                    },
                    "html": {
                        "icon": "jstree-file"
                    }
                },
                "plugins": ["types", "search", "unique"]
            }).on("changed.jstree", function (e, data) {
                // 表格重新加载
                if (data.selected.length > 0) {
                    $("#groupTable").bootstrapTable('refreshOptions', {pageNumber: 1});
                    $("#groupTable").bootstrapTable("refresh");
                }
            });
        },
        loopMenu: function (array, isModel) {
            if (array && array.length > 0) {
                for (var i = 0; i < array.length; i++) {
                    var children = array[i]["children"];
                    if (children.length <= 0) {
                        array[i].type = "html"
                    } else {
//                        array[i].state = {"opened": false}
                    }
                    if (isModel) {
                        array[i].state = {"opened": false}
                    } else {
                        array[i].state = {"opened": true}
                    }
                    if (children) {
                        orgTree.loopMenu(children, true);
                    }
                }
                return array;
            } else {
                return [];
            }
        },
        jloopMenu: function (array, isModel) {
            if (array && array.length > 0) {
                for (var i = 0; i < array.length; i++) {
                    var children = array[i]["children"];
                    if (children.length <= 0) {
                        array[i].type = "html"
                    } else {
//                        array[i].state = {"opened": false}
                    }
                    if (isModel) {
                        array[i].state = {"opened": true}
                    } else {
                        array[i].state = {"opened": true}
                    }
                    if (children) {
                        orgTree.jloopMenu(children, true);
                    }
                }
                return array;
            } else {
                return [];
            }
        }
    };

    /*【由授权功能替换】
     // 数据范围设定（即指定质检组与坐席组之间的关系）
     var qcRelationFun = {
     addInit: function () {
     $("#addRelationDiv").css("display", "none");
     $("#addRelationListDiv").html("");
     },
     editInit: function () {
     $("#editRelationDiv").css("display", "none");
     $("#editRelationListDiv").html("");
     }
     };*/

    // 批量导入
    var importfile = {
        init: function () {
            importfile.importModalInit();
            importfile.ifile();
            importfile.areaTips();
        },
        importModalInit: function () {
            $("#importModal").on("show.bs.modal", function () {
                // 初始化省份信息
                $.get(basePath + "rest/area/showAllAreas", function (data) {
                    if (data != null) {
                        $("#importForm :input[name='areaid']").html("");
                        $.get(basePath + "rest/area/getAreaInfo", function (areaInfo) {
                            if (areaInfo == null || areaInfo == "") {
                                $("#importForm :input[name='areaid']").append("<option value='' selected>请选择</option>");
                            }
                            $.each(data, function (index, area) {
                                $("#importForm :input[name='areaid']").append("<option value='" + area.id + "'>" + area.area + "</option>");
                            });
                            $("#importForm :input[name='areaid']").selectpicker('refresh');
                            var areaVal = $("#importForm :input[name='areaid']").selectpicker('val');
                            if (areaVal != "") {
                                $(".importTips").css("display", "none");
                            }
                        });
                    }
                });
                // 初始化文件上传控件
                $("#uploadDiv").html("").append("<div class='file-loading'><input id='uploadFile' name='uploadFile' type='file' /></div><div id='errorBlock' class='help-block'></div>");
                $("#uploadFile").fileinput({
                    language: 'zh',
                    uploadUrl: basePath + "rest/group/batchImportGroup",
                    allowedFileExtensions: ['xls', 'xlsx'],
                    elErrorContainer: '#errorBlock',
                    showPreview: false,
                    showUpload: false,
                    maxFileCount: 1,
                    enctype: 'multipart/form-data',
                    uploadExtraData: function (previewId, index) {
                        var data = {
                            areaid: $("#importForm :input[name='areaid']").val()
                        };
                        return data;
                    }
                }).on("fileuploaded", function (event, data, previewId, index) {
                    var response = data.response;
                    if (response.type == "success") {
                        $("#importModal").modal("hide");
                        toastr.success(response.message);
                        //刷新table和左侧树
                        $("#groupTable").bootstrapTable("refresh");
                        $("#organizTree").jstree("refresh");
                    } else {
                        toastr.error(response.message);
                    }
                });
            });
        },
        ifile: function () {
            $("#importConfirmBtn").off("click").on("click", function () {
                var areaid = $('#importForm :input[name="areaid"] option:selected').val();
                var file = $("#uploadFile").val();
//                // 校验省份
//                if (areaid == "") {
//                    toastr.error("请选择省份");
//                    return false;
//                }
                if (file == "") {
                    toastr.error("请选择要上传的文件");
                    return false;
                }
                /*else if (file.substring(file.lastIndexOf(".")) != ".xls") {
                 toastr.error("上传文件格式错误，请使用低版本excel文件");
                 return false;
                 }*/
                // 校验通过上传
                $("#uploadFile").fileinput("upload");
            });
        },
        areaTips: function () {
            $("#importForm :input[name='areaid']").on("change", function () {
                if ($(this).selectpicker("val") == "") {
                    $(".importTips").css("display", "block");
                } else {
                    $(".importTips").css("display", "none");
                }
            });
        },
    }
    //    授权
    var power = {
        jstreeRData: [],
        init: function () {
            $("#powerBtn").on("click", function () {
                var rows = $("#groupTable").bootstrapTable("getSelections");
                if (rows.length == 0 || rows.length > 1 || (rows.length == 1 && rows[0].type != 1)) {
                    toastr.error('请选择一条类型为质检的组织机构信息');
                } else {
                    // 所选质检组id
                    var id = rows[0].id;
                    // 取出该质检组所设置的坐席组的信息
                    $("#powerModal").modal("show").attr("data-id", id);
                    power.jstreeRData = [];
                    $(".boxP input").val("");
                    power.initTree($("#jstreeL"), basePath + "rest/group/selectUnAuthSeatGroup");
                    power.initTree($("#jstreeR"), basePath + "rest/group/selectAuthSeatGroup");
                    power.search($("#jstreeL"));
                    power.search($("#jstreeR"));
                }
            });
            power.unAuthon();
        },
        initTree: function (elem, url) {
            var rows = $("#groupTable").bootstrapTable("getSelections");
            var areaname = rows[0].areaname;
            // 树初始化
            elem.jstree("destroy");
            elem.data('jstree', false).empty();
            elem.jstree({
                "core": {
                    "animation": false,
                    "multiple": true,
                    "check_callback": true,
                    'data': function (obj, callback) {
                        $.ajax({
                            type: "GET",
                            url: url,
                            dataType: "json",
                            data: {
                                groupId: $("#powerModal").attr("data-id")
                            },
                            success: function (result) {
                                if (result != null && result.length > 0) {
                                    if (elem.attr("id") == "jstreeR") {
                                        power.jstreeRData = [];
                                    }
                                    var arr = [];
                                    if (areaname == null) {
                                        areaname = "集团";
                                    }
                                    reformResult = [{
                                        "areaId": -1,
                                        "area": areaname,
                                        "allGroupList": result
                                    }];

                                    for (var i = 0; i < reformResult.length; i++) {
                                        var obj = {};
                                        obj.id = reformResult[i].areaId;
                                        obj.text = reformResult[i].area;
                                        obj.flag = 0;//标识能不能传参到后台；0：不能，1：能
                                        obj.children = [];
                                        var allGroupList = reformResult[i].allGroupList;
                                        for (var j = 0; j < allGroupList.length; j++) {
                                            var obj1 = {};
                                            obj1.id = allGroupList[j].parentId;
                                            obj1.text = allGroupList[j].parentName;
                                            obj1.flag = 0;//标识能不能传参到后台
                                            obj1.children = [];
                                            var groupList = allGroupList[j].seatGroupList;
                                            if (groupList.length > 0) {
                                                for (var k = 0; k < groupList.length; k++) {
                                                    var obj2 = {};
                                                    obj2.id = groupList[k].id;
                                                    if (elem.attr("id") == "jstreeR") {
                                                        power.jstreeRData.push(obj2.id);
                                                    }
                                                    obj2.text = groupList[k].name;
                                                    obj2.flag = 1;
                                                    obj2.children = [];
                                                    if (obj1.id == null) {
                                                        obj.children.push(obj2);
                                                    } else {
                                                        obj1.children.push(obj2);
                                                    }
                                                }
                                            }
                                            if (obj.id == null) {
                                                arr.push(obj1);
                                            } else {
                                                if (obj1.id == null) {
                                                    continue;
                                                } else {
                                                    obj.children.push(obj1);
                                                }
                                            }
                                        }
                                        if (obj.id != null) {
                                            arr.push(obj)
                                        }
                                    }

                                }
                                callback.call(this, orgTree.jloopMenu(arr));
                            }
                        });
                    }
                },
                "types": {
                    "default": {
                        "icon": "jstree-folder"
                    },
                    "html": {
                        "icon": "jstree-file"
                    }
                },
                "plugins": ["types", "search", "unique", "checkbox"],
                "checkbox": {
                    "keep_selected_style": false
                }
            }).on("loaded.jstree", function (e, data) {

            });
        },
        search: function (elem) {
            var btn = elem.prev().find(".fa_btn");
            var input = elem.prev().find("input");
            btn.on("click", function () {
                elem.jstree(true).search(input.val());
                power.scrollSearch(elem);
            });
            input.on("keyup", function (e) {
                var code = e.charCode || e.keyCode;
                if (code == 13) {
                    elem.jstree(true).search(input.val());
                    power.scrollSearch(elem);
                }
            })
        },
        scrollSearch: function (elem) {
            if (elem.find(".jstree-search").length > 0) {
                var odiv = elem.find(".jstree-search").eq(0)[0];
                var top = odiv.offsetTop;
                var height = odiv.offsetHeight;
                var elemTop = elem[0].scrollTop;
                //获取当前屏幕大小
                var size = elem.height();
                //加上元素本身的高度，是元素全部出现事件
                if ((top + height) < (elemTop + size) && (top + height) > elemTop) {

                } else {
                    elem.animate({scrollTop: top - 70}, "slow");
                }
            }
        },
        unAuthon: function () {
            $("#authon").on("click", function () {//授权操作
                power.authonMethods("authon", $("#jstreeL"));
            });
            $("#unAuthon").on("click", function () {//撤销授权操作
                power.authonMethods("unAuthon", $("#jstreeR"));
            });
        },
        authonMethods: function (type, elem) {
            var nodeIds = power.getSelectNodeId(type, elem);
            if ($("#powerModal").attr("data-check") == "false") {
                toastrCog.error("请选择需要授权的数据", 2000)
                return
            }
            $.ajax({
                type: "GET",
                url: basePath + "rest/group/qcRelationSave",
                dataType: "json",
                traditional: true,
                data: {
                    qcGroupId: $("#powerModal").attr("data-id"),
                    seatGroupIdList: nodeIds
                },
                success: function (result) {
                    if (result && result.type == "success") {
                        toastrCog.success("授权成功", 1000);
                        power.initTree($("#jstreeL"), basePath + "rest/group/selectUnAuthSeatGroup");
                        power.initTree($("#jstreeR"), basePath + "rest/group/selectAuthSeatGroup");
                    } else {
                        toastrCog.error("授权失败")
                    }
                }
            });
        },
        getSelectNodeId: function (type, elem) {
            var treeNode = elem.jstree(true); //获取所有选中的节点对象
            treeNode.get_all_checked = function () { //返回所有选中的节点id
                var tmp = new Array;
                for (var i in this._model.data) {
                    if (this.is_undetermined(i) || this.is_checked(i)) {
                        if (this._model.data[i].id != "#") {
                            var node = this._model.data[i];
                            if (node.original.flag == 1) {
                                tmp.push(node.id);
                            }
                        }
                    }
                }
                return tmp;
            };
            var nodeIds = treeNode.get_all_checked();//获取所有选中的节点id
            if (nodeIds.length > 0) {//用来判断有没有选中的节点
                $("#powerModal").attr("data-check", "true")
            } else {
                $("#powerModal").attr("data-check", "false")
            }
            var authonAllNode = power.jstreeRData;//获取所有已授权id
            if (type == "authon") {//授权操作
                nodeIds = nodeIds.concat(authonAllNode);
            } else {//撤销授权操作
                var index;
                for (var j = 0; j < nodeIds.length; j++) {
                    index = authonAllNode.indexOf(parseInt(nodeIds[j]));
                    if (index > -1) {
                        authonAllNode.splice(index, 1);
                    }
                }
                nodeIds = authonAllNode;
            }
            return nodeIds;
        }
    };
    var resize = {
        init: function () {
            resize.me();
            $(window).resize(function () {
                resize.me();
            })
        },
        me: function () {
            var winW = $(window).width();
            var winH = $(window).height();
            $(".ibox").width(winW - 20);
            $(".ibox").height(winH - 20);
            $("#organizTree").height(winH - 55);
            bs.autoTableHeight($('#groupTable'),winH -$(".cquery").height()-22-$(".obtns").height())
        }
    };

    // 查询机构类型在页面新增和修改组织机构modal中进行展示
    var groupTypeFun = {
        // 查询用户状态
        init: function () {
            // 获取所有用户状态 并拼接option
            var str = "";
            $.each(groupTypeList, function (i, e) {
                str += "<option value=\"" + e.value + "\">" + e.name + "</option>";
            });
            // 给每个下拉框进行初始化
            $("#addType").html(str).selectpicker('refresh');
            $("#editType").html(str).selectpicker('refresh');
            $("#mechanismType").html(str).selectpicker('refresh');
        }
    };

    $(function () {
        // 先初始化树 才能正常加载table
        orgTree.init();
        // 初始化页面上所有组织机构下拉选择框
        groupTypeFun.init();
        // 表格初始化
        var oTable = new TableInit();
        oTable.Init();
        baseFun.init();
        groupStatusChangeFun.init();
        groupDeleteFun.init();
        groupAddFun.init();
        groupEditFun.init();
        validateFun.init();
        importfile.init();
        power.init();
        resize.init();
    });
    //点击空白处
    $(document).click(function (e) {
        var _con = $("input[name='parentname'],.otree");
        if (!_con.is(e.target) && _con.has(e.target).length === 0) {
            $('.otree ').hide();
        }
    });
</script>
</body>
</html>